package com.fourierlab.ibator.plugins;

import java.util.List;

import org.apache.ibatis.ibator.api.IbatorPluginAdapter;
import org.apache.ibatis.ibator.api.IntrospectedTable;
import org.apache.ibatis.ibator.api.dom.java.FullyQualifiedJavaType;
import org.apache.ibatis.ibator.internal.util.StringUtility;
import org.apache.ibatis.ibator.internal.util.messages.Messages;

public class BaseDaoPlugin extends IbatorPluginAdapter {
	private static String DEFAULT_BASE_DAO_PATTERN = "I%sBaseDao";
	private static String DEFAULT_BASE_DAO_IMPL_PATTERN = "%sBaseDaoImpl";
	private static String BASE_DAO_PATTERN = "baseDaoPattern";
	private static String BASE_DAO_IMPL_PATTERN = "baseDaoImplPattern";
	

	public BaseDaoPlugin() {
		super();
	}
	
	/* (non-Javadoc)
	 * @see org.apache.ibatis.ibator.api.IbatorPlugin#validate(java.util.List)
	 */
	public boolean validate(List<String> warnings) {
        boolean valid = true;
        
        if (!StringUtility.stringHasValue(properties.getProperty("targetProject"))) {
            warnings.add(Messages.getString("Warning.25"));
            valid = false;
        }
        
        if (!StringUtility.stringHasValue(properties.getProperty("targetPackage"))) {
            warnings.add(Messages.getString("Warning.26"));
            valid = false;
        }
        
        return valid;
	}

	/* (non-Javadoc)
	 * @see org.apache.ibatis.ibator.api.IbatorPluginAdapter#initialized(org.apache.ibatis.ibator.api.IntrospectedTable)
	 */
	@Override
	public void initialized(IntrospectedTable introspectedTable) {
		super.initialized(introspectedTable);
		introspectedTable.setAttribute(IntrospectedTable.ATTR_DAO_IMPLEMENTATION_TYPE, calculateDaoImpl(introspectedTable));
		introspectedTable.setAttribute(IntrospectedTable.ATTR_DAO_INTERFACE_TYPE, calculateDao(introspectedTable));
	}
	
	private FullyQualifiedJavaType calculateDaoImpl(IntrospectedTable introspectedTable) {
		return new FullyQualifiedJavaType(introspectedTable.getDAOImplementationPackage() + "." + String.format(properties.getProperty(BASE_DAO_IMPL_PATTERN, DEFAULT_BASE_DAO_IMPL_PATTERN), introspectedTable.getFullyQualifiedTable().getDomainObjectName()));
	}
	
	private FullyQualifiedJavaType calculateDao(IntrospectedTable introspectedTable) {
		return new FullyQualifiedJavaType(introspectedTable.getDAOInterfacePackage() + "." + String.format(properties.getProperty(BASE_DAO_PATTERN, DEFAULT_BASE_DAO_PATTERN), introspectedTable.getFullyQualifiedTable().getDomainObjectName()));
	}
}
